<!--
  @author:  long
  @date:    2023/3/29
  @file:    xx
  @require:
-->
<template>
  <div class="seasonSetUp">
    <el-form :rules="rules" ref="formRef" :model="form" label-width="80">
      <el-row>
        <el-col :span="24">
          <el-form-item label="年度">
            <div class="flex items-center justify-between w-full">
              <el-date-picker
                v-model="form.year"
                type="year"
                placeholder="请选择年份"
                :disabled-date="setYearDisabledDate"
                value-format="YYYY"
                format="YYYY"
                @change="selectChange"
              />
              <el-button @click="handleSave" type="primary">保存</el-button>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="24" v-for="(item, index) in formItems" :key="index">
          <el-form-item :label="item.label">
            <div class="flex items-center justify-between w-full">
              <el-date-picker
                v-model="form[item.prop]"
                type="daterange"
                style="width: 100%"
                class="mr-2"
                ref="formDetaRef"
                value-format="YYYY-MM-DD"
                format="YYYY-MM-DD"
                start-placeholder="开始时间"
                @change="
                  val => {
                    daterangeChange(val, item.prop)
                  }
                "
                end-placeholder="结束时间"
                :default-value="item.defaultValue"
                :disabled-date="
                  time => {
                    return setDisabledDate(time, index)
                  }
                "
              />
              <el-input
                v-model="form[item.prop1]"
                placeholder="备注"
              ></el-input>
            </div>
          </el-form-item>
          <el-form-item label="" :prop="item.prop2">
            <div class="w-full">
              <el-select
                multiple
                v-model="form[item.prop2]"
                class="w-full"
                placeholder="请选择考核结果将写入的月份，必须3个月，选过的月份不可再选"
                @change="
                  val => {
                    monthSelectChange(val, item.prop2)
                  }
                "
              >
                <el-option
                  v-for="(item, index) in item.monthOptions"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                  :disabled="item.disabled"
                >
                </el-option>
              </el-select>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script setup name="seasonSetUp">
import { getCurrentInstance } from 'vue'
import { format, startOfMonth, endOfMonth } from 'date-fns'
import {
  getScheduleInfo,
  saveScheduleInfo
} from '@/api/officeManage/evaluation'
import useUserStore from '@/store/modules/user'
const { proxy } = getCurrentInstance()
const userStore = useUserStore()

const props = defineProps({
  year: {
    type: String,
    default: ''
  }
})

const validateMonths = (rule, value, callback) => {
  switch (rule.field) {
    case 'firstMonths':
      let firstFlag = checkTime('firstTime')
      if (firstFlag) {
        if (value.length < 3) {
          callback(new Error('考核结果月必须选择3个月'))
        } else {
          callback()
        }
      } else {
        callback()
      }
      break
    case 'secondMonths':
      let secondFlag = checkTime('secondTime')
      if (secondFlag) {
        if (value.length < 3) {
          callback(new Error('考核结果月必须选择3个月'))
        } else {
          callback()
        }
      } else {
        callback()
      }
      break
    case 'thirdMonths':
      let thirdFlag = checkTime('thirdTime')
      if (thirdFlag) {
        if (value.length < 3) {
          callback(new Error('考核结果月必须选择3个月'))
        } else {
          callback()
        }
      } else {
        callback()
      }
      break
    case 'fourthMonths':
      let fourthFlag = checkTime('fourthTime')

      if (fourthFlag) {
        if (value.length < 3) {
          callback(new Error('考核结果月必须选择3个月'))
        } else {
          callback()
        }
      } else {
        callback()
      }
      break
  }
}

const checkTime = prop => {
  if (typeof form.value[prop] === 'object') {
    if (form.value[prop] != null) {
      if (form.value[prop][0] != null && form.value[prop][0] != '') {
        return true
      } else {
        return false
      }
    } else {
      return false
    }
  } else if (typeof form.value[prop] === 'string') {
    if (form.value[prop] != null && form.value[prop] != '') {
      return true
    } else {
      return false
    }
  }
}

const data = reactive({
  form: {
    year: format(new Date(), 'yyyy'),
    firstTime: [],
    firstRemark: '',
    firstMonths: [],
    secondTime: [],
    secondRemark: '',
    secondMonths: [],
    thirdTime: [],
    thirdRemark: '',
    thirdMonths: [],
    fourthTime: [],
    fourthRemark: '',
    fourthMonths: []
  },
  rules: {
    firstMonths: [{ validator: validateMonths, trigger: 'change' }],
    secondMonths: [{ validator: validateMonths, trigger: 'change' }],
    thirdMonths: [{ validator: validateMonths, trigger: 'change' }],
    fourthMonths: [{ validator: validateMonths, trigger: 'change' }]
  },

  formItems: [
    // 一月到十二月
    {
      label: '第一季度',
      prop: 'firstTime',
      prop1: 'firstRemark',
      prop2: 'firstMonths',
      defaultValue: [],
      id: '',
      monthOptions: []
    },
    {
      label: '第二季度',
      prop: 'secondTime',
      prop1: 'secondRemark',
      prop2: 'secondMonths',
      defaultValue: [],
      id: '',
      monthOptions: []
    },
    {
      label: '第三季度',
      prop: 'thirdTime',
      prop1: 'thirdRemark',
      prop2: 'thirdMonths',
      defaultValue: [],
      id: '',
      monthOptions: []
    },
    {
      label: '第四季度',
      prop: 'fourthTime',
      prop1: 'fourthRemark',
      prop2: 'fourthMonths',
      defaultValue: [],
      id: '',
      monthOptions: []
    }
  ]
})
const { form, formItems, monthOptions, rules } = toRefs(data)
const { month_dict } = proxy.useDict('month_dict')
const emits = defineEmits(['closeDrawer'])

watchEffect(
  () => {
    if (month_dict.value.length > 0) {
      let month = JSON.parse(JSON.stringify(month_dict.value))
      filterMonth(month)
    }
  },
  { flush: 'post' }
)

const daterangeChange = (val, prop) => {
  if (val == null) {
    form.value[prop] = ''
  }
}

/**
 * 过滤月份
 */
const filterMonth = month => {
  formItems.value.forEach(item => {
    item.monthOptions = month
  })
  monthSelectChange()
}

/**
 *设置form表单数据显示
 */
const setInfoData = (data, year = format(new Date(), 'yyyy')) => {
  if (data.length > 0) {
    data.forEach((item, index) => {
      form.value[formItems.value[index].prop] = [
        item.assessStime,
        item.assessEtime
      ]
      form.value[formItems.value[index].prop1] = item.assessRemark
      form.value[formItems.value[index].prop2] =
        item.resultInMonth != null && item.resultInMonth != ''
          ? item.resultInMonth.split(',')
          : ''
      formItems.value[index].id = item.id
    })
  } else {
    form.value = {
      year: year,
      firstTime: [],
      firstRemark: '',
      firstMonths: [],
      secondTime: [],
      secondRemark: '',
      secondMonths: [],
      thirdTime: [],
      thirdRemark: '',
      thirdMonths: [],
      fourthTime: [],
      fourthRemark: '',
      fourthMonths: []
    }
    formItems.value.forEach(item => {
      item.id = ''
    })
  }
}

/**
 * @description: 保存
 */
const handleSave = () => {
  proxy.$refs.formRef.validate(valid => {
    console.info('valid', valid)
    if (valid) {
      let params = []
      formItems.value.forEach((item, index) => {
        let obj = {
          orgId: userStore.user.orgId,
          deptId: userStore.user.deptId,
          assessAtYear: form.value.year,
          assessStime: '',
          assessEtime: '',
          assessStatus: '0',
          assessRemark: form.value[item.prop1],
          resultInMonth:
            form.value[item.prop2].length > 0
              ? form.value[item.prop2].map(item => item).join(',')
              : '',
          scheduleType: '1',
          id: item.id,
          assessAtTime: index + 1
        }
        if (form.value[item.prop] != null && form.value[item.prop].length > 0) {
          obj.assessStime =
            form.value[item.prop][0] != null
              ? form.value[item.prop][0] + ' 00:00:00'
              : ''
          obj.assessEtime =
            form.value[item.prop][1] != null
              ? form.value[item.prop][1] + ' 23:59:59'
              : ''
        }
        params.push(obj)
      })

      //   保存考评日历
      saveScheduleInfo(params).then(res => {
        if (res.code === 200) {
          proxy.$modal.msgSuccess(res.msg)
          emits('closeDrawer', form.value.year)
        }
      })
    } else {
    }
  })
}

/**
 * 设置年份禁用日期
 */
const setYearDisabledDate = (time, index) => {
  let year = format(new Date(), 'yyyy') * 1
  let pre = new Date(year - 5 + '-01-01')
  let nex = new Date(year + 5 + '-12-31')
  return time < pre || time > nex
}

/**
 * @description: 月份选择
 */
const monthSelectChange = (val, type) => {
  //   获取form表单字段
  let valArr = ['firstMonths', 'secondMonths', 'thirdMonths', 'fourthMonths']

  formItems.value.forEach((item, index) => {
    //   获取非当前数据字段
    let arr = valArr.filter(t => t != item.prop2)
    let array = []
    //   获取非当前数据字段的select值
    arr.forEach(t => {
      array = array.concat(form.value[t])
    })
    let monthOptions = JSON.parse(JSON.stringify(item.monthOptions))
    //   根据数据设置select禁用
    monthOptions.map(t => {
      if (array.includes(t.value)) {
        t.disabled = true
      } else {
        t.disabled = false
      }
    })
    item.monthOptions = monthOptions.sort((a, b) => a.value - b.value)
  })
  if (val) {
    form.value[type] = val.sort()
  }
}

/**
 * @description: 设置禁用日期
 *
 */
const setDisabledDate = (time, index) => {
  // return (
  //   time.getTime() < formItems.value[index].defaultValue[0].getTime() ||
  //   time.getTime() > formItems.value[index].defaultValue[1].getTime()
  // )
}

/**
 * @description: 年份改变111
 */
const selectChange = () => {
  setDefaultTime()
  handleCalendarQuery()
}

/**
 * @description: 查询考评日历（季度）
 */
const handleCalendarQuery = () => {
  let params = {
    orgId: userStore.user.orgId,
    deptId: userStore.user.deptId,
    scheduleType: '1',
    assessAtYear: form.value.year
  }

  getScheduleInfo(params).then(res => {
    let data =
      res.data == null || res.data.length == 0
        ? []
        : res.data.sort((ar1, ar2) => ar1.assessAtTime - ar2.assessAtTime)
    setInfoData(data, form.value.year)
  })
}

/**
 * 设置默认时间
 */
const setDefaultTime = () => {
  formItems.value.forEach((item, index) => {
    // 根据index获取到3

    let l = `${form.value.year}-${(index + 1) * 3 - 2}`
    let r = `${form.value.year}-${(index + 1) * 3}`
    item.defaultValue = [startOfMonth(new Date(l)), endOfMonth(new Date(r))]
  })
}
/**
 * 初始化
 */
const init = async () => {
  //   设置年份
  form.value.year = props.year
  //   设置默认时间
  setDefaultTime()

  //   查询考评日历
  await handleCalendarQuery()
}
init()
</script>

<style scoped lang="scss"></style>
